package com.uni.controller;

import com.uni.entity.Dto;
import com.uni.entity.ShopUser;
import com.uni.service.AuthService;
import com.uni.util.DtoUtil;
import com.uni.util.FastDFSClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user/consumer")
public class UserController {

    @Autowired
    private AuthService authService;

    public static final String fileSystemAddress = "http://47.114.97.182/";

    /**
     * 分页查询
     * @param page 页码
     * @param limit 每页条数
     * @return page
     */
    @GetMapping("/getPage")
    public Dto userList(Integer page, Integer limit){
        log.info("page:{} limit:{} userList", page, limit);
        return authService.userList(page, limit);
    }

    /**
     * 根据id查询
     * @param id
     * @return 用户信息
     */
    @GetMapping("/get/{id}")
    public Dto getUserById(@PathVariable("id") Long id){
        log.info("id:{} getUserById", id);
        Dto result = authService.getUserById(id);
        return result;
    }

    /**
     * 删除用户
     * @param ids id列表
     * @return 响应
     */
    @GetMapping("/delete")
    public Dto deleteUserById(@RequestParam("ids") List<Long> ids){
        log.info("id:{} deleteUserById", ids);
        return authService.deleteUserById(ids);
    }

    /**
     * 更新用户信息
     * @param user 实例对象
     * @return 响应
     */
    @PostMapping("/update")
    public Dto update(@RequestBody ShopUser user){
        log.info("update user");
        return authService.update(user);
    }

    /**
     * 用户头像上传
     * @param file
     * @param url 如果有旧图片需要替换
     * @return 图片地址
     */
    @PostMapping("/uploadAvatar")
    public Dto uploadImg(MultipartFile file, String url){
        if (file.isEmpty()) {
            return DtoUtil.returnFail("文件为空","500");
        }
        if(!StringUtils.isEmpty(url)){
            String substring = url.substring(20);
            String[] split = substring.split("/");
            FastDFSClientUtils.delete(split[0],substring);
        }
        try {
            //上传图片并返回url
            return DtoUtil.returnSuccess("上传成功",
                    FastDFSClientUtils.upload(file.getBytes(),file.getOriginalFilename())
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("上传失败，请联系管理员","500");
    }

    /**
     * 用户注销
     * @param request 请求体
     * @return 响应
     */
    @GetMapping("/logout")
    public Dto logout(HttpServletRequest request){
        return DtoUtil.returnSuccess("注销成功");
    }

}
